package com.hfy.user.service.impl;

import com.hfy.model.po.user.UserPo;
import com.hfy.user.mapper.RegisterMapper;
import com.hfy.user.service.RegisterService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import result.Result;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static constants.OSSConstants.*;

/**
 * @ author 韩
 * time: 2024/5/12 21:21
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private RegisterMapper registerMapper;


//    @Autowired
//    private KafkaTemplate<String,String> kafkaTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Result register(MultipartFile avatar, String username, String password) {
        // 验证密码长度
        if (!isValidPassword(password)) {
            return Result.error("昵称或密码必须由3~15字符组成！");
        }
        // 验证昵称长度
        if (!isValidUsername(username)) {
            return Result.error("昵称或密码必须由3~15个字符组成！");
        }
        // 条件许可 开始注册 生成一个账号，再查看有没有该账号如果有就再生成一个
        Long account = getAccount();

        UserPo user = registerMapper.selectByAccount(account);
        // 有该账号 重新创建
        while (user != null) {
            account = getAccount();
            user = registerMapper.selectByAccount(account);
        }

        // 头像文件名
        String avatarName = OSS_COVER_PREFIX + account + OSS_COVER_PREFIX;

        String avatarSqlName =  OSS_HTTPS_PREFIX + OSS_BUCKET_NAME + "."  + OSS_ENDPOINT + "/" + OSS_AVATAR_USER_PREFIX + account + OSS_AVATAR_USER_PREFIX;
        // 直到账号确定了下来 然后调用mapper方法进行账号创建
        try {
            registerMapper.register(avatarSqlName,account,username,password);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("sql执行错误");
        }





        return Result.ok("账号创建成功，请记牢你的账号是 " + account + "\n你的密码是 " + password);
    }


    private Long getAccount() {
        Random random = new Random();
        long randomNumber = random.nextInt(9) + 1;
        for (int i = 0; i < 10; i++) {
            randomNumber = randomNumber * 10 + random.nextInt(10);
        }
        return randomNumber;
    }

    // 验证密码长度的方法
    private boolean isValidPassword(String password) {
        // 密码长度范围为3~15个字符
        Pattern pattern = Pattern.compile("^\\S{3,15}$");
        Matcher matcher = pattern.matcher(password);
        return matcher.matches();
    }

    // 验证用户名长度的方法
    private boolean isValidUsername(String username) {
        // 用户名长度范围为3~15个字符
        Pattern pattern = Pattern.compile("^\\S{3,15}$");
        Matcher matcher = pattern.matcher(username);
        return matcher.matches();
    }


}
